<?php
/**
 * @author GhostWei
 * @date Sep 16, 2012
 */
class community_oauth_concept extends system_concept_abstract {
	
	public function __construct($source_id = null) {
		$where = $value = array();
		if($source_id !== null) {
			$where = array('source_id' => $source_id);
			$value = array('source_id = ?' => $source_id);
		}
		parent::__construct($where, $value);
	}
	
	public function init() {
		$this->setRowClass('community_oauth_row');
		$this->setModel('community_oauth_model', 'oauth');
		$this->setModelCols('oauth', array('source_id', 'passport_id', 'access_token', 'uid', 'app_id', 'app_key', 'attribute'));
		$this->setModelCols('oauth', array('creationip', 'expiredtime', 'creationtime', 'modifiedtime'));
	}
	
	public function save(community_oauth_row $row) {
		if(!($passport = system_passport_instance::getRow($row->getPassportId()))) {
			throw new community_exception("passport can not be empty");
		}
		if(!$row->getAccessToken()) {
			throw new community_exception("access token formation error");
		}
		if(!$row->getAppKey()) {
			throw new community_exception("app key formation error");
		}
		if(!$row->getAppId()) {
			throw new community_exception("app id can not be empty");
		}
		if(!$row->getExpiredtime()) {
			$row->setExpiredtime(0);
		}
		if($this->fetch(array('passport_id = ?' => $passport->getId()))) {
			$row->setModifiedtime(system_date::timestamp());
			$row->update();
		} else {
			$time = system_date::timestamp();
			$row->setCreationtime($time);
			$row->setModifiedtime($time);
			$this->getModel('oauth')->insert($row->getModelData('oauth'));
		}
		return $row;
	}

	
}
